package com.kevinpascoe.apps.loneworker;

import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.net.Uri;
import android.preference.RingtonePreference;
import android.provider.ContactsContract;
import android.util.AttributeSet;

public class SelectContactPreference extends RingtonePreference {
	 public interface OnPhonePickedListener {
	        void onPhonePicked(Uri uri);
	    }

	    private OnPhonePickedListener mPhonePickedListener;
	    
	    public SelectContactPreference(Context context, AttributeSet attrs, int defStyle) {
	        super(context, attrs, defStyle);
	        
	        TypedArray a = context.obtainStyledAttributes(attrs,
	                R.styleable.SelectContactPreference, defStyle, 0);
	        
	        a.recycle();
	    }

	    public SelectContactPreference(Context context, AttributeSet attrs) {
	        this(context, attrs, R.styleable.Theme_seectContactPreferenceStyle);
	    }
	    
	    public SelectContactPreference(Context context) {
	        super(context);
	    }

	    public void setOnPhonePickedListener(OnPhonePickedListener listener) {
	        if (listener != null) {
	            mPhonePickedListener = listener;
	        }
	    }
	    
	    @Override 
	    protected void onPrepareRingtonePickerIntent(Intent intent) {
	        // Override this intent to start ContactsListActivity
	        intent.setAction(Intent.ACTION_GET_CONTENT);
	        intent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
	        intent.setFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
	    }
	   
	    @Override                                                                       
	    public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
	        if (super.onActivityResult(requestCode, resultCode, data)) {
	            if (data != null) {
	                Uri uri = data.getData();
	                if (callChangeListener(uri != null ? uri.toString() : "")) {
	                    onSaveRingtone(uri);
	                }
	            }
	            return true;
	        }
			return false;
	    }

	    protected void onSaveRingtone(Uri uri) {
	        super.onSaveRingtone(uri);
	        if (mPhonePickedListener != null) {
	            mPhonePickedListener.onPhonePicked(uri);
	        }
	    }
}
